package com.sixth.service.impl;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sixth.entity.User;
import com.sixth.dao.UserDao;
import com.sixth.service.UserService;
import com.sixth.until.CommonResult;
import com.sixth.until.WebUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * @program: self-tui-education
 * @description:
 * @author: 高振杨
 * @create: 2022-04-14 17:37
 **/
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Bean //创建一个密码加密器的对象交于spring容器来管理
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    @Override
    public User findByUsername(String username) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        User user = userDao.selectOne(wrapper);
        return user;
    }
    @Override
    public CommonResult updateUserPassword(String oldPassword, String newPassword) {
        String token = WebUtil.getRequest().getHeader("token");
        String encode = passwordEncoder.encode(newPassword);
        if(StringUtils.hasText(token)){
            String id = JWT.require(Algorithm.HMAC256("gzy-lpp")).build().verify(token).getClaim("userid").asString();
            User user = userDao.selectById(id);
            String password = user.getPassword();
            boolean matches = passwordEncoder.matches(oldPassword,password);
            if(matches){
                int row=userDao.updateUserPassword(id,encode);
                return new CommonResult(2000,"修改成功",null);
            }
            return new CommonResult(5000,"旧密码有误",null);
        }
        return new CommonResult(5000,"修改失败",null);
    }
}
